<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat } from '@/hooks/util'
import * as imApi from '@/api/im'
import { message } from 'ant-design-vue'
import AddIM from './components/AddIM.vue'
import CorrelationList from './components/CorrelationList.vue'
import AssociatedList from './components/AssociatedList.vue'
import LdleFish from './LdleFish.vue'

const route = useRoute()

const addIMRef = ref()
const correlationListRef = ref()
const AssociatedListRef = ref()

const activeKey = ref<string>('1')

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  channel: number
  currentPage: number
  pageSize: number
  robotId?: string | undefined
  customerId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
}
const searchParams = ref<SearchParams>({
  channel: 1,
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref<Array<any>>([])
const columns = [
  {
    key: 'customerId',
    width: 150,
  },
  {
    title: '所属用户',
    key: 'userId',
    width: 150,
  },
  {
    title: '备注',
    key: 'remark',
    width: 150,
  },
  {
    title: '关联微信账号数量',
    key: 'robotCount',
    width: 150,
    align: 'center',
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 180,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 90,
  },
]
// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  // console.log('selectedRowKey=', selectedRowKeys)
  selectedRowKey.value = selectedRowKeys

  selectedRow.value = selectedRows
  console.log('selectedRow=', selectedRow.value)
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}
const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}
const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await imApi.getCustomerList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => getList())

// 查询
const formRef = ref()
import type { SelectProps } from 'ant-design-vue'
interface FormState {
  robotId?: string | undefined
  customerId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    // console.log('formState=', formState)
    searchParams.value.robotId = formState.robotId || ''
    searchParams.value.customerId = formState.customerId || ''
    searchParams.value.nickName = formState.nickName || ''
    searchParams.value.remark = formState.remark || ''
    // console.log('searchParams=', searchParams.value)
    getList()
  })
}

// 重置
const reset = () => {
  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'robotId')
  Reflect.deleteProperty(searchParams.value, 'customerId')
  Reflect.deleteProperty(searchParams.value, 'nickName')
  Reflect.deleteProperty(searchParams.value, 'remark')

  getList()
}

// 修改备注
const editRemark = async (id: string, remark: string) => {
  let params = {
    id,
    remark,
  }
  try {
    const { state, message: msg } = await imApi.editCustomerRemark(params)
    if (state === 200) {
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 删除
const del = async (id: string) => {
  try {
    let { state, message: msg } = await imApi.deleteCustomer({
      id,
    })
    if (state === 200) {
      message.success('已删除')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 关联微信账号
const correlation = (id: string) => {
  correlationListRef.value.showModal(id)
}

// 已关联微信账号
const associated = (id: string) => {
  AssociatedListRef.value.showModal(id)
}

// 添加初语客服
const addIM = () => {
  addIMRef.value.showModal()
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-alert type="warning" style="margin-bottom: 10px">
      <template #description>
        <span>
          念初旗下，集成式IM客服系统，拥有高并发、高可靠的即时通信能力，关联后重启客户端软件生效！
          <a href="http://im.liangpiao.net.cn/" target="_blank">点击前往客服工作台</a>
        </span>
      </template>
    </a-alert>

    <a-card style="overflow-x: scroll">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="闲鱼" force-render>
          <LdleFish></LdleFish>
        </a-tab-pane>
        <a-tab-pane key="2" tab="微信">
          <div class="searchBox">
            <a-form ref="formRef" layout="inline" :model="formState">
              <a-form-item label="微信账号ID" name="robotId">
                <a-input v-model:value="formState.robotId" placeholder="微信账号ID" />
              </a-form-item>

              <a-form-item label="客服ID" name="customerId">
                <a-input v-model:value="formState.customerId" placeholder="客服ID" />
              </a-form-item>

              <a-form-item label="昵称" name="nickName">
                <a-input v-model:value="formState.nickName" placeholder="昵称" />
              </a-form-item>

              <a-form-item label="备注" name="remark">
                <a-input v-model:value="formState.remark" placeholder="备注" />
              </a-form-item>
            </a-form>
            <a-button type="primary" style="border-radius: 6px" @click="search">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="reset" style="border-radius: 6px">重置</a-button>
          </div>
          <div style="margin: 5px 0">
            <a-button style="border-radius: 6px" type="primary" @click="addIM">
              新增初语账户
            </a-button>
          </div>

          <a-alert
            description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
            type="info"
            banner
            style="margin-bottom: 10px; padding: 10px"
          />

          <a-table
            style="overflow-x: scroll"
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            @change="changePage"
            rowKey="id"
          >
            <!-- :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }" -->
            <template #emptyText>
              <a-empty description="暂无数据" />
            </template>

            <template #headerCell="{ column }">
              <template v-if="column.key === 'customerId'">
                <span>客服ID</span>
              </template>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'customerId'">
                <div style="width: 150px">{{ record.customerId }}</div>
              </template>

              <template v-else-if="column.key === 'userId'">
                <div style="width: 150px">{{ record.userId }}</div>
              </template>

              <template v-else-if="column.key === 'remark'">
                <div style="display: flex; align-items: center">
                  <div>备注：</div>
                  <span v-if="!record.isRemarkShow">{{ record.remark }}</span>
                  <a-input
                    v-else
                    v-model:value="record.remark"
                    @blur="editRemark(record.id, record.remark)"
                    style="width: 160px; border: 0"
                  />
                  <div>
                    <EditOutlined
                      @click="EditRemarkSet(record)"
                      v-if="!record.isRemarkShow"
                      style="margin-left: 10px; color: #1890ff"
                    />
                  </div>
                </div>
              </template>

              <template v-else-if="column.key === 'robotCount'">
                <a-tag color="red" style="cursor: pointer" @click="correlation(record.id)">
                  {{ record.robotCount }}
                </a-tag>
              </template>

              <template v-else-if="column.key === 'updateTime'">
                <div style="width: 160px">{{ timeFormat(record.updateTime) }}</div>
              </template>

              <template v-else-if="column.key === 'createTime'">
                <div style="width: 160px">{{ timeFormat(record.createTime) }}</div>
              </template>

              <template v-else-if="column.key === 'action'">
                <div style="width: 100px; margin: 0; padding: 0">
                  <a @click="correlation(record.id)">关联微信账号</a>
                  <br />
                  <a @click="associated(record.id)">已关联微信账号</a>
                  <br />
                  <a-popconfirm
                    title="您确认要删除吗？"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="del(record.id)"
                  >
                    <a>删除</a>
                  </a-popconfirm>
                </div>
              </template>
            </template>
          </a-table>

          <AddIM ref="addIMRef" @refresh="getList"></AddIM>
          <CorrelationList ref="correlationListRef" @refresh="getList"></CorrelationList>
          <AssociatedList ref="AssociatedListRef" @refresh="getList"></AssociatedList>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.searchBox {
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>

<style lang="less">
.ant-form-inline .ant-form-item {
  margin-bottom: 10px !important;
}
</style>
